package com.example.finaltask;

import static com.example.finaltask.utils.Check.checkEmail;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.finaltask.modle.User;
import com.example.finaltask.utils.DBHelper;
import com.example.finaltask.utils.MD5;
import com.example.finaltask.utils.Remove;

import java.io.Serializable;

public class LoginActivity extends Activity {
    private DBHelper dbhelper;

    private TextView title;

    private Button login;
    private Button signUp;

    private ImageView headImage;
    private FrameLayout passwordFrame;

    private View background;

    private ImageView clearEmail;
    private ImageView seePWD;

    private EditText email;
    private EditText password;

    private boolean isShow = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Remove.removeTop(this);

        title = findViewById(R.id.login_title);
        //按钮
        login = findViewById(R.id.login_confirm);
        signUp = findViewById(R.id.signUp_button);
        //头像
        headImage = findViewById(R.id.head_image_login);
        //密码
        passwordFrame = findViewById(R.id.login_password);
        //图片按钮
        clearEmail = findViewById(R.id.clear_login);
        seePWD = findViewById(R.id.see_login);
        //背景
        background = findViewById(R.id.login_background);
        //文本框
        email = findViewById(R.id.login_email_text);
        password = findViewById(R.id.login_password_text);
        //表单监听器
        formEditListener();
        //获取Intent传递过来的数据
        User user;
        Intent intent = getIntent();
        user = (User) intent.getSerializableExtra("user");
        initInfo(user);
    }

    public void initInfo(User user) {
        if (user != null) {
            title.setVisibility(View.INVISIBLE);
            headImage.setVisibility(View.VISIBLE);
            email.setText(user.getEmail());
            password.setText(user.getPassword());
            //设置用户头像
            Glide.with(this).load(user.getHeadImage()).into(headImage);
        }
    }

    /**
     * @description 判断邮箱是否被注册
     */
    public boolean emailUnique() {
        int count = 0;
        DBHelper dbhelper = new DBHelper(LoginActivity.this, "murmur.db", null, 7);
        SQLiteDatabase db = dbhelper.getWritableDatabase();
        Cursor cursor = db.query("user", new String[]{"email"}, "email=?",
                new String[]{email.getText().toString()}, null, null, null);
        if (count != 0) {
            return false;
        }
        return true;
    }

    /**
     * @description 表单监听器
     */
    public void formEditListener() {
        //焦点监听器
        email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                int count = 0;
                if (!hasFocus && checkEmail(email.getText().toString())) {
                    DBHelper dbhelper = new DBHelper(LoginActivity.this, "murmur.db", null, 7);
                    SQLiteDatabase db = dbhelper.getWritableDatabase();
                    Cursor cursor = db.query("user", new String[]{"email"}, "email=?",
                            new String[]{email.getText().toString()}, null, null, null);
                    while (cursor.moveToNext()) {
                        count++;
                    }
                    if (count == 0) {
                        title.setVisibility(View.VISIBLE);
                        headImage.setVisibility(View.INVISIBLE);
                        Toast.makeText(getBaseContext(), "邮箱尚未注册", Toast.LENGTH_LONG).show();
                    } else {
                        while (cursor.moveToNext()) {
                            User user = new User();
                            user.setUserName(cursor.getString(cursor.getColumnIndex("userName")));
                            user.setEmail(cursor.getString(cursor.getColumnIndex("email")));
                            user.setPassword(cursor.getString(cursor.getColumnIndex("password")));
                            user.setHeadImage(cursor.getString(cursor.getColumnIndex("headImage")));
                            //设置用户头像
                            Glide.with(LoginActivity.this).load(user.getHeadImage()).into(headImage);
                            title.setVisibility(View.INVISIBLE);
                            headImage.setVisibility(View.VISIBLE);
                        }
                        cursor.close();
                    }
                } else if (!hasFocus && !checkEmail(email.getText().toString())) {
                    title.setVisibility(View.VISIBLE);
                    headImage.setVisibility(View.INVISIBLE);
                }
            }
        });
        //清除邮箱
        clearEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                email.setText("");
                title.setVisibility(View.VISIBLE);
                headImage.setVisibility(View.INVISIBLE);
            }
        });
        //密码可见性切换
        seePWD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果密码可见
                if (isShow) {
                    //切换图标
                    seePWD.setBackground(getDrawable(R.drawable.ic_eye_close));
                    //设置密码不可见
                    password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                    //改变状态值为假
                    isShow = false;
                } else {
                    //切换图标
                    seePWD.setBackground(getDrawable(R.drawable.ic_eye));
                    //设置密码可见
                    password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    //改变状态值为真
                    isShow = true;
                }
            }
        });
        //立即注册
        signUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转注册
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, SignUpActivity.class);
                intent.putExtra("email", email.getText().toString());
                startActivity(intent);
                finish();
            }
        });
        //登录按钮
        login.setOnClickListener(new View.OnClickListener() {
            int count = 0;

            @Override
            public void onClick(View v) {
                DBHelper dbhelper = new DBHelper(LoginActivity.this, "murmur.db", null, 7);
                SQLiteDatabase db = dbhelper.getWritableDatabase();
                Cursor cursor = db.query("user", new String[]{"email"}, "email=?",
                        new String[]{email.getText().toString()}, null, null, null);
                while (cursor.moveToNext()) {
                    count++;
                }
                if (count != 0) {
                    User user = new User();
                    while (cursor.moveToNext()) {
                        user.setId(cursor.getInt(cursor.getColumnIndex("id")));
                        user.setUserName(cursor.getString(cursor.getColumnIndex("username")));
                        user.setEmail(cursor.getString(cursor.getColumnIndex("email")));
                        user.setPassword(cursor.getString(cursor.getColumnIndex("password")));
                        user.setHeadImage(cursor.getString(cursor.getColumnIndex("headimage")));
                    }
                    String passwordMD5 = MD5.getMD5String(password.getText().toString());
                    //登录验证
                    //if (user.getPassword().equals(passwordMD5)) {
                            //跳转登录页面,传递对象
                            Intent intent = new Intent();
                            intent.setClass(LoginActivity.this, IndexActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("user", user);
                            intent.putExtras(bundle);
                            startActivity(intent);
                            finish();
                        }
                    //} else {
                        //Toast.makeText(getBaseContext(), "邮箱或密码错误", Toast.LENGTH_LONG).show();
                    //}
                }
        });
    }
}